<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Render函数</title>
</head>

<body>
    <div id="app"></div>
    <script>
        // 渲染普通标签元素
        const vnode = {
            tag: 'div',
            props: {
                onClick: () => console.log('ok')
            },
            children: [
                {
                    tag: 'span',
                    children: '点我'
                },
                {
                    tag: 'p',
                    children: '123'
                }]
        }

        function mountElement(vnode, container) {
            const el = document.createElement(vnode.tag)
            for (let key in vnode.props) {
                if ((/^on/).test(key)) {
                    let event = key.toLocaleLowerCase().substr(2)
                    el.addEventListener(event, vnode.props[key])
                }
            }
            if (typeof vnode.children === 'string') {
                const textNode = document.createTextNode(vnode.children)
                el.appendChild(textNode)
            } else if (Array.isArray(vnode.children)) {
                vnode.children.forEach(child => renderer(child, el))
            }
            container.appendChild(el)
        }

        // 渲染组件 
        const myComponent = {
            render() {
                return {
                    tag: 'div',
                    props: {
                        onClick: () => console.log(111)
                    },
                    children: 'click me'
                }
            }
        }

        const vnode2 = {
            tag: myComponent
        }

        function mountComponent(vnode, container) {
            const subtree = vnode.tag.render()
            renderer(subtree, container)
        }

        function renderer(vnode, container) {
            if (typeof vnode.tag === 'string') {
                mountElement(vnode, container)
            } else if (typeof vnode.tag === 'object') {
                mountComponent(vnode, container)
            }
        }

        renderer(vnode, document.querySelector('#app'))
        renderer(vnode2, document.querySelector('#app'))

    </script>
</body>

</html>